03 May, 2019
np.unique() function is used to find the unique elements of an array. It returns the sorted unique elements of an array. It can also return three other optional outputs-
Example: Return unique values of an array
import numpy as np
np.unique([1,2,2,3,3,4,5,5,5,6,6,7])
Output:
array([1, 2, 3, 4, 5, 6, 7])
Example: Defining an array and getting unique values of it
a = np.array([[1, 1], [2, 3],[3,3])
np.unique(a)
Output:
array([1, 2, 3])
Example: Return unique rows of a 2D array
a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
np.unique(a,axis=0)
Output:
array([[1, 0, 0],
[2, 3, 4]])
Example: Return indices of original array which gives unique values
a = np.array(['a', 'b', 'b', 'c', 'a'])
u, indices = np.unique(a, return_index=True)
u
Output:
array(['a', 'b', 'c'], dtype='<U1')
Example: : Return indices of original array which gives unique values
indices
Output:
array([0, 1, 3], dtype=int64)
Example: Return indices of original array which gives unique values
a[indices]
Output:
array(['a', 'b', 'c'], dtype='<U1')